package com.example.pojo;

import java.util.HashMap;

/**
 * 通用泛型返回结果封装类
 */
public class AjaxResult<T> extends HashMap<String, Object> {

    public static final String CODE_TAG = "code";
    public static final String MSG_TAG = "msg";
    public static final String DATA_TAG = "data";

    // 成功状态码
    public static final int SUCCESS = 200;
    // 失败状态码
    public static final int ERROR = 500;
    // 参数错误
    public static final int PARAM_ERROR = 400;

    public AjaxResult() {}

    /**
     * 成功返回，无数据
     */
    public static <T> AjaxResult<T> success() {
        return AjaxResult.success("操作成功", null);
    }

    /**
     * 成功返回，带消息
     */
    public static <T> AjaxResult<T> success(String msg) {
        return AjaxResult.success(msg, null);
    }

    /**
     * 成功返回，带数据
     */
    public static <T> AjaxResult<T> success(T data) {
        return AjaxResult.success("操作成功", data);
    }

    /**
     * 成功返回，带消息和数据
     */
    public static <T> AjaxResult<T> success(String msg, T data) {
        AjaxResult<T> result = new AjaxResult<>();
        result.put(CODE_TAG, SUCCESS);
        result.put(MSG_TAG, msg);
        if (data != null) {
            result.put(DATA_TAG, data);
        }
        return result;
    }

    /**
     * 失败返回，无码
     */
    public static <T> AjaxResult<T> fail() {
        return AjaxResult.error(ERROR, "操作失败");
    }

    /**
     * 失败返回，指定消息
     */
    public static <T> AjaxResult<T> fail(String msg) {
        return AjaxResult.error(ERROR, msg);
    }

    /**
     * 失败返回，指定状态码和消息
     */
    public static <T> AjaxResult<T> error(int code, String msg) {
        AjaxResult<T> result = new AjaxResult<>();
        result.put(CODE_TAG, code);
        result.put(MSG_TAG, msg);
        return result;
    }

    /**
     * 参数错误
     */
    public static <T> AjaxResult<T> paramError(String msg) {
        return AjaxResult.error(PARAM_ERROR, msg);
    }

    /**
     * 构造器设置泛型数据
     */
    public static <T> AjaxResult<T> build(int code, String msg, T data) {
        AjaxResult<T> result = new AjaxResult<>();
        result.put(CODE_TAG, code);
        result.put(MSG_TAG, msg);
        if (data != null) {
            result.put(DATA_TAG, data);
        }
        return result;
    }

    // 为了兼容 Map 的 put 方法
    public Object put(String key, Object value) {
        super.put(key, value);
        return value;
    }
}